import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:lottie/lottie.dart';
import 'dart:math';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:async'; // 用于Timer类
import '../animation_feedback.dart';

// 关卡操作类型枚举
enum OperationType {
  addition,
  subtraction,
  multiplication,
  division,
}

// 关卡类
class Level {
  final int id;
  final int requiredScore;
  final int timeLimit;
  final int maxMistakes;
  final OperationType operation;
  final int operandRange;
  final bool allowNegative;

  const Level({
    required this.id,
    required this.requiredScore,
    required this.timeLimit,
    this.maxMistakes = 2,
    this.operation = OperationType.addition,
    this.operandRange = 10,
    this.allowNegative = false,
  });
}

// Extract timer display to separate widget
class _TimerDisplay extends StatefulWidget {
  final int timeLimit;

  const _TimerDisplay({
    required this.timeLimit,
    required GlobalKey<_TimerDisplayState> key,
  });

  @override
  State<_TimerDisplay> createState() => _TimerDisplayState();
}

class _TimerDisplayState extends State<_TimerDisplay> {
  late Timer _timer;
  int _elapsedTime = 0;

  // Add method to stop timer externally
  void stopTimer() {
    if (_timer.isActive) {
      _timer.cancel();
    }
  }

  @override
  void initState() {
    super.initState();
    _startTimer();
  }

  @override
  void dispose() {
    _timer.cancel();
    super.dispose();
  }

  void _startTimer() {
    _elapsedTime = 0;
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (mounted) {
        setState(() {
          print("计时器: setState5 $_elapsedTime");
          _elapsedTime++;
          if (_elapsedTime >= widget.timeLimit) {
            _showTimeUpDialog();
          }
        });
      }
    });
  }

  void _showTimeUpDialog() {
    _timer?.cancel();

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('时间到！'),
        content: const Text('你没有在规定时间内完成关卡。'),
        actions: [
          TextButton(
            onPressed: () {
              Navigator.pop(context);
              //_resetGame();
            },
            child: const Text('重试'),
          )
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final remainingTime = widget.timeLimit - _elapsedTime;
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Icon(remainingTime < 10 ? Icons.timer_off : Icons.timer,
            color: remainingTime < 10 ? Colors.red : Colors.blue),
        Text('$remainingTime秒', style: const TextStyle(fontSize: 18)),
      ],
    );
  }
}

class MathBrickGame extends StatefulWidget {
  final String? selectedLevelId; // Add this line

  const MathBrickGame({super.key, this.selectedLevelId}); // Modify this line

  @override
  State<MathBrickGame> createState() => _MathBrickGameState();
}

class _MathBrickGameState extends State<MathBrickGame> {
  // Add this constant for debug logging control
  static const bool _enableDebugLogs = true;
  final GlobalKey<_TimerDisplayState> _timerKey = GlobalKey();

  // 在 _MathBrickGameState 类中添加数据模型和状态变量
  late AudioPlayer _audioPlayer;
  final Random _random = Random();

  // 原有状态变量
  int _num1 = 0;
  int _num2 = 0;
  String _operator = '+';
  //int _score = 0;
  int? _userAnswer;
  bool _answered = false;
  IconData _feedbackIcon = Icons.check_circle;
  Color _feedbackColor = Colors.green;
  List<int> _options = [];
  bool _isCorrect = false;

  // 新增状态标记
  bool _isInitialized = false;

  // 新增关卡相关状态变量
  int _currentLevel = 1;
  int _currentScore = 0;
  int _mistakesMade = 0;
  late DateTime _levelStartTime;
  bool _isLevelCompleted = false;

  // 当前关卡配置
  late Level _currentLevelConfig = const Level(
    id: 1,
    requiredScore: 5,
    timeLimit: 60,
    operandRange: 10,
    operation: OperationType.addition,
  );

  // 在 initState 中加载进度
  @override
  void initState() {
    super.initState();
    print("initState");
    // 初始化音频播放器
    print("initState, Initializing AudioPlayer");
    _audioPlayer = AudioPlayer();

    print("initState, SharedPreferences.getInstance");
    // 加载历史进度
    SharedPreferences.getInstance().then((prefs) {
      print("SharedPreferences loaded");
      setState(() {
        _currentLevel = prefs.getInt('currentLevel') ?? 1;
        print("initState, setState6, _currentLevel: $_currentLevel");
      });

      // 重新初始化关卡配置以确保正确性
      _initializeLevelConfig();
    });
    print("initState, WidgetsBinding.instance.addPostFrameCallback");
    // 确保在UI构建完成后进行初始化
    WidgetsBinding.instance.addPostFrameCallback((_) {
      print("WidgetsBinding.instance.addPostFrameCallback, mounted: $mounted");
      if (mounted) {
        _initializeLevelConfig();
      }
    });
  }

  Level _createLevelConfig(int level) {
    print("_createLevelConfig, level: $level");

    // 计算所属类别和难度等级
    final categoryIndex = (level - 1) ~/ 3; // 5个类别，每个类别3个级别
    final difficultyIndex = (level - 1) % 3; // 3个难度等级

    // 根据难度等级确定操作类型
    OperationType operation;
    if (categoryIndex == 0) {
      operation = OperationType.addition;
    } else if (categoryIndex == 1) {
      operation = OperationType.subtraction;
    } else if (categoryIndex == 2) {
      operation = OperationType.multiplication;
    } else if (categoryIndex == 3) {
      operation = OperationType.division;
    } else if (categoryIndex == 4) {
      // 综合类别随机选择一种操作
      final randomOp = _random.nextInt(4);
      switch (randomOp) {
        case 0:
          operation = OperationType.addition;
          break;
        case 1:
          operation = OperationType.subtraction;
          break;
        case 2:
          operation = OperationType.multiplication;
          break;
        case 3:
          operation = OperationType.division;
          break;
        default:
          operation = OperationType.addition;
      }
    } else {
      operation = OperationType.addition;
    }

    // 根据难度等级确定参数范围
    int operandRange;
    bool allowNegative = false;
    int requiredScore;
    int timeLimit;

    switch (difficultyIndex) {
      case 0: // 初级
        operandRange = 10;
        requiredScore = 5;
        timeLimit = 60;
        break;
      case 1: // 中级
        operandRange = 20;
        requiredScore = 10;
        timeLimit = 90;
        break;
      case 2: // 高级
        operandRange = 30;
        requiredScore = 15;
        timeLimit = 120;
        allowNegative = true;
        break;
      default:
        operandRange = 10;
        requiredScore = 5;
        timeLimit = 60;
    }

    return Level(
      id: level,
      requiredScore: requiredScore,
      timeLimit: timeLimit,
      operation: operation,
      operandRange: operandRange,
      allowNegative: allowNegative,
    );
  }

  void _initializeLevelConfig() {
    print("_initializeLevelConfig");
    // 获取关卡ID
    String levelId = widget.selectedLevelId ?? '加法1';
    print("_initializeLevelConfig, 选中的关卡ID: $levelId");

    // 解析关卡ID获取关卡数字
    final levelNumber = int.tryParse(levelId.replaceAll(RegExp(r'[^0-9]'), ''));
    print("_initializeLevelConfig, 解析关卡ID得到的关卡数字: $levelNumber");

    // 创建默认关卡配置
    Level newLevelConfig = const Level(
      id: 1,
      requiredScore: 5,
      timeLimit: 60,
      operandRange: 10,
      operation: OperationType.addition,
    );

    // 根据解析结果确定关卡级别
    if (levelNumber != null && levelNumber > 0 && levelNumber <= 15) {
      _currentLevel = levelNumber;
    }

    print("当前关卡: $_currentLevel");
    // 使用统一的关卡配置创建逻辑
    newLevelConfig = _createLevelConfig(_currentLevel);

    setState(() {
      print("setState61: _currentLevelConfig = $newLevelConfig");
      _currentLevelConfig = newLevelConfig;
      _currentScore = 0;
      _mistakesMade = 0;
      _isLevelCompleted = false;

      // 根据新关卡配置生成题目
      if (_currentLevelConfig.operation == OperationType.addition) {
        _num1 = _random.nextInt(_currentLevelConfig.operandRange) + 1;
        _num2 = _random.nextInt(_currentLevelConfig.operandRange) + 1;
      } else if (_currentLevelConfig.operation == OperationType.subtraction) {
        // 确保非负数结果
        _num1 = _random.nextInt(_currentLevelConfig.operandRange) + 1;
        _num2 = _random.nextInt(_num1) + 1;
      } else if (_currentLevelConfig.operation ==
          OperationType.multiplication) {
        // 乘法使用较小的数值范围
        _num1 = _random.nextInt(operandRangeForMultiplication) + 1;
        _num2 = _random.nextInt(operandRangeForMultiplication) + 1;
      } else if (_currentLevelConfig.operation == OperationType.division) {
        // 确保除法能整除
        _num2 = _random.nextInt(operandRangeForDivision) + 1;
        _num1 = _num2 * (_random.nextInt(operandRangeForDivision) + 1);
      }

      _userAnswer = null;
      _answered = false;
      _operator = _getOperatorSymbol(_currentLevelConfig.operation);

      // 计算正确答案并生成选项
      final correctAnswer = _calculateCorrectAnswer();
      print("setState8: $_num1 $_operator $_num2 = $correctAnswer");
      print("setState9: correctAnswer = $correctAnswer");
      _options = _generateOptions(correctAnswer);

      // 标记为已初始化
      _isInitialized = true;
    });
  }

  /*void _resetGame() {
    print("_resetGame");
    setState(() {
      _score = 0;
    });
    print("选项: _resetGame");
    _generateQuestion();
  }*/

  @override
  void dispose() {
    _audioPlayer.dispose();
    super.dispose();
  }

  Future<void> _playSound(bool isCorrect) async {
    try {
      await _audioPlayer.play(
        AssetSource('audio/${isCorrect ? 'taibang.mp3' : 'oo.mp3'}'),
      );
    } catch (e) {
      // 日志记录已移除
    }
  }

  void _showLevelCompleteDialog() {
    print("_showLevelCompleteDialog");
    _timerKey.currentState?.stopTimer(); // 停止计时器

    // 播放通关音效
    //_playSound(true);
    // 显示通关动画
    setState(() {
      print("_showLevelCompleteDialog: setState10");
      _isLevelCompleted = true;
    });

    // 播放通关动画后自动进入下一关
    Future.delayed(const Duration(seconds: 2), () async {
      final int nextLevel = _currentLevel + 1;

      // 如果已经是最后一关，直接返回主界面
      if (nextLevel > 15) {
        Navigator.pop(context);
        return;
      }

      // 保存进度
      final prefs = await SharedPreferences.getInstance();
      await prefs.setInt('currentLevel', nextLevel);
      await prefs.setString('加法$_currentLevel', 'completed'); // 保存当前关卡为已完成

      // 跳转到下一关页面
      Navigator.pushReplacement(
        context,
        MaterialPageRoute(
          builder: (context) => MathBrickGame(selectedLevelId: '加法$nextLevel'),
        ),
      );
    });
  }

  // 在 generateQuestion 方法中确保定时器正确启动
  void _generateNewQuestion() {
    print("_generateQuestion");
    setState(() {
      final levelConfig = _currentLevelConfig;
      print("_generateQuestion: setState11, 当前关卡配置: $levelConfig");

      // 根据关卡运算类型生成题目
      if (levelConfig.operation == OperationType.addition) {
        _num1 = _random.nextInt(levelConfig.operandRange) + 1;
        _num2 = _random.nextInt(levelConfig.operandRange) + 1;
      } else if (levelConfig.operation == OperationType.subtraction) {
        // 确保非负数结果
        _num1 = _random.nextInt(levelConfig.operandRange) + 1;
        _num2 = _random.nextInt(_num1) + 1;
      } else if (levelConfig.operation == OperationType.multiplication) {
        // 乘法使用较小的数值范围
        _num1 = _random.nextInt(operandRangeForMultiplication) + 1;
        _num2 = _random.nextInt(operandRangeForMultiplication) + 1;
      } else if (levelConfig.operation == OperationType.division) {
        // 确保除法能整除
        _num2 = _random.nextInt(operandRangeForDivision) + 1;
        _num1 = _num2 * (_random.nextInt(operandRangeForDivision) + 1);
      }

      _userAnswer = null;
      _answered = false;
      _operator = _getOperatorSymbol(levelConfig.operation);

      // 计算正确答案并生成选项
      final correctAnswer = _calculateCorrectAnswer();
      print("_generateQuestion, $_num1 $_operator $_num2 = $correctAnswer");
      _options = _generateOptions(correctAnswer);
    });
  }

  /*void _checkAnswer() {
    print("_checkAnswer");
    if (_userAnswer == null) {
      print("_checkAnswer: 用户未选择答案");
      return;
    }

    final correctAnswer = _calculateCorrectAnswer();
    final isCorrect = _userAnswer == correctAnswer;

    setState(() {
      print("_checkAnswer: setState0 $setState");
      _isCorrect = isCorrect;
      _answered = true;
      
      if (isCorrect) {
        _currentScore++;
        print("_checkAnswer: 用户回答正确，当前得分 $_currentScore");
        _playSound(true);
        _feedbackIcon = Icons.check_circle;
        _feedbackColor = Colors.green;
        
        // 检查是否通关
        if (_currentScore >= _currentLevelConfig.requiredScore) {
          _showLevelCompleteDialog(); // 显示通关提示
        }
      } else {
        print("_checkAnswer: 用户回答错误");
        _playSound(false);
        _feedbackIcon = Icons.error;
        _feedbackColor = Colors.red;
        _mistakesMade++;
      }
    });
    
    // 仅在答题正确时生成新题目
    if (isCorrect) {
      print("_checkAnswer: isCorrect = $isCorrect");
      Future.delayed(const Duration(seconds: 1), () {
        print("_checkAnswer: 生成新题目");
        _generateNewQuestion();
        // 重置回答状态和用户答案
        setState(() {
          print("_checkAnswer: setState1 $setState");
          _answered = false;
          _userAnswer = null;
        });
      });
    } else if (_mistakesMade >= _currentLevelConfig.maxMistakes) {
      Future.delayed(const Duration(seconds: 1), () {
        print("_checkAnswer: 玩家失败");
        _generateNewQuestion();
        // 重置回答状态和用户答案
        setState(() {
          print("_checkAnswer: setState2 $setState");
          _answered = false;
          _userAnswer = null;
        });
      });
    }
  }*/
// 修改后的 _checkAnswer 方法
  void _checkAnswer() {
    print("_checkAnswer");
    if (_userAnswer == null) {
      print("_checkAnswer: 用户未选择答案");
      return;
    }

    final correctAnswer = _calculateCorrectAnswer();
    final isCorrect = _userAnswer == correctAnswer;

    setState(() {
      print("_checkAnswer: setState0 $setState");
      _isCorrect = isCorrect;
      _answered = true;

      if (isCorrect) {
        _currentScore++;
        print("_checkAnswer: 用户回答正确，当前得分 $_currentScore");
        _playSound(true);
        _feedbackIcon = Icons.check_circle;
        _feedbackColor = Colors.green;

        // 检查是否通关
        if (_currentScore >= _currentLevelConfig.requiredScore) {
          _showLevelCompleteDialog(); // 显示通关提示
        }
      } else {
        print("_checkAnswer: 用户回答错误");
        _playSound(false);
        _feedbackIcon = Icons.error;
        _feedbackColor = Colors.red;
        _mistakesMade++;
      }
    });

    // 添加动画反馈
    if (!isCorrect) {
      // 使用动画控制器显示分步计算过程
      final animationFeedback = AnimationFeedback(context);
      animationFeedback.startMakeTenAnimation(
        num1: _num1,
        num2: _num2,
        correctAnswer: correctAnswer,
      );
    }

    // 仅在答题正确时生成新题目
    if (isCorrect) {
      print("_checkAnswer: isCorrect = $isCorrect");
      Future.delayed(const Duration(seconds: 1), () {
        print("_checkAnswer: 生成新题目");
        _generateNewQuestion();
        // 重置回答状态和用户答案
        setState(() {
          print("_checkAnswer: setState1 $setState");
          _answered = false;
          _userAnswer = null;
        });
      });
    } else if (_mistakesMade >= _currentLevelConfig.maxMistakes) {
      Future.delayed(const Duration(seconds: 1), () {
        print("_checkAnswer: 玩家失败");
        _generateNewQuestion();
        // 重置回答状态和用户答案
        setState(() {
          print("_checkAnswer: setState2 $setState");
          _answered = false;
          _userAnswer = null;
        });
      });
    }
  }

  int _generateWrongAnswer(int correctAnswer) {
    int wrongAnswer;
    do {
      wrongAnswer =
          (correctAnswer + _random.nextInt(5) * (_random.nextBool() ? 1 : -1))
              .toInt(); // Fix: Add .toInt()
    } while (wrongAnswer == correctAnswer);
    print("_generateWrongAnswer: $wrongAnswer");
    return wrongAnswer;
  }

  List<int> _generateOptions(int correctAnswer) {
    print("_generateOptions: $correctAnswer");
    final options = <int>{};
    options.add(correctAnswer);

    // 添加随机干扰项，确保选项数量达到4个
    while (options.length < 4) {
      // 生成合理范围内的随机数（±正确答案值的50%）
      var range = max(5, correctAnswer ~/ 2);
      int min = max(0, correctAnswer - range);
      int maxVal = correctAnswer + range;
      print("_generateOptions, min: $min, maxVal: $maxVal");
      // 生成随机值，确保不是负数（除非允许负数）
      int randomValue = _random.nextInt(maxVal - min + 1) + min;

      // 如果允许负数，则可能生成负数选项
      if (_currentLevelConfig.allowNegative && _random.nextBool()) {
        randomValue = -randomValue;
      }
      print("_generateOptions, randomValue: $randomValue");
      // 确保不会意外移除正确答案
      if (randomValue != correctAnswer) {
        options.add(randomValue);
      }
    }

    // 验证正确答案是否在选项中
    if (!options.contains(correctAnswer)) {
      options.remove(correctAnswer); // 移除可能存在的旧值
      options.add(correctAnswer); // 确保正确答案始终在选项中
    }

    // 将Set转换为List并随机排序
    return options.toList()..shuffle();
  }

  // 构建关卡信息指示器
  Widget _buildLevelInfoIndicator() {
    print("_buildLevelInfoIndicator: 当前关卡 $_currentLevel");
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        const Icon(Icons.star, color: Colors.amber),
        Text('第$_currentLevel关 - 目标：${_currentLevelConfig.requiredScore}分',
            style: const TextStyle(fontSize: 18)),
      ],
    );
  }

  // 在 _MathBrickGameState 类中添加以下常量和方法
  static const int operandRangeForMultiplication = 12; // 乘法使用较小的数值范围（1-12）
  static const int operandRangeForDivision = 10; // 除法使用较小的数值范围

  // 根据操作类型获取运算符符号
  String _getOperatorSymbol(OperationType operation) {
    switch (operation) {
      case OperationType.addition:
        return '+';
      case OperationType.subtraction:
        return '-';
      case OperationType.multiplication:
        return '×';
      case OperationType.division:
        return '÷';
      default:
        return '?';
    }
  }

  // 计算正确答案
  int _calculateCorrectAnswer() {
    switch (_currentLevelConfig.operation) {
      case OperationType.addition:
        return _num1 + _num2;
      case OperationType.subtraction:
        return _num1 - _num2;
      case OperationType.multiplication:
        return _num1 * _num2;
      case OperationType.division:
        return _num1 ~/ _num2;
      default:
        return 0;
    }
  }

  // 修改 _switchLevel 方法以支持所有操作类型
  void _switchLevel(int level) {
    print("_switchLevel: level = $level");
    setState(() {
      print("setState3 $setState");

      _currentLevel = level;
      _currentScore = 0;
      _mistakesMade = 0;

      // 根据新关卡配置生成题目
      if (_currentLevelConfig.operation == OperationType.addition) {
        _num1 = _random.nextInt(_currentLevelConfig.operandRange) + 1;
        _num2 = _random.nextInt(_currentLevelConfig.operandRange) + 1;
      } else if (_currentLevelConfig.operation == OperationType.subtraction) {
        // 确保非负数结果
        _num1 = _random.nextInt(_currentLevelConfig.operandRange) + 1;
        _num2 = _random.nextInt(_num1) + 1;
      } else if (_currentLevelConfig.operation ==
          OperationType.multiplication) {
        // 乘法使用较小的数值范围
        _num1 = _random.nextInt(operandRangeForMultiplication) + 1;
        _num2 = _random.nextInt(operandRangeForMultiplication) + 1;
      } else if (_currentLevelConfig.operation == OperationType.division) {
        // 确保除法能整除
        _num2 = _random.nextInt(operandRangeForDivision) + 1;
        _num1 = _num2 * (_random.nextInt(operandRangeForDivision) + 1);
      }

      _userAnswer = null;
      _answered = false;
      _operator = _getOperatorSymbol(_currentLevelConfig.operation);

      // 计算正确答案并生成选项
      final correctAnswer = _calculateCorrectAnswer();
      print("_switchLevel: $_num1  $_operator $_num2 = $correctAnswer");
      _options = _generateOptions(correctAnswer);
    });
  }

  // 修改 _generateQuestion 方法以支持所有操作类型
  void _generateQuestion() {
    print("_generateQuestion");
    setState(() {
      final levelConfig = _currentLevelConfig;
      print("_generateQuestion: setState11, 当前关卡配置: $levelConfig");

      // 根据关卡运算类型生成题目
      if (levelConfig.operation == OperationType.addition) {
        _num1 = _random.nextInt(levelConfig.operandRange) + 1;
        _num2 = _random.nextInt(levelConfig.operandRange) + 1;
      } else if (levelConfig.operation == OperationType.subtraction) {
        // 确保非负数结果
        _num1 = _random.nextInt(levelConfig.operandRange) + 1;
        _num2 = _random.nextInt(_num1) + 1;
      } else if (levelConfig.operation == OperationType.multiplication) {
        // 乘法使用较小的数值范围
        _num1 = _random.nextInt(operandRangeForMultiplication) + 1;
        _num2 = _random.nextInt(operandRangeForMultiplication) + 1;
      } else if (levelConfig.operation == OperationType.division) {
        // 确保除法能整除
        _num2 = _random.nextInt(operandRangeForDivision) + 1;
        _num1 = _num2 * (_random.nextInt(operandRangeForDivision) + 1);
      }

      _userAnswer = null;
      _answered = false;
      _operator = _getOperatorSymbol(levelConfig.operation);

      // 计算正确答案并生成选项
      final correctAnswer = _calculateCorrectAnswer();
      print("_generateQuestion, $_num1 $_operator $_num2 = $correctAnswer");
      _options = _generateOptions(correctAnswer);
    });
  }

  @override
  Widget build(BuildContext context) {
    // 计算正确答案（在build方法中）
    final correctAnswer = _calculateCorrectAnswer();
    print("build: $_num1  $_operator $_num2 = $correctAnswer");
    // 确保_options已初始化
    print("build: _options = $_options");
    // 如果_options未初始化或为空，则生成新的选项
    if (_options == null || _options.isEmpty) {
      _options = _generateOptions(correctAnswer);
      print("build: _options = $_options");
    }
    print("build: _options = $_options");
    // 获取当前答题状态
    final isCorrect = _userAnswer != null && _userAnswer == correctAnswer;
    print(
        "build: isCorrect = $isCorrect, _userAnswer = $_userAnswer, correctAnswer = $correctAnswer");

    return Scaffold(
      backgroundColor: Colors.yellow[200],
      appBar: AppBar(
        title: const Text('数学积木'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            if (_isLevelCompleted)
              Center(
                child: Lottie.asset(
                  'assets/animations/level_complete.json',
                  width: 200,
                  height: 200,
                  fit: BoxFit.contain,
                  repeat: false,
                ),
              )
            else ...[
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Container(
                    width: 60,
                    height: 60,
                    decoration: BoxDecoration(
                      color: Colors.yellow[700],
                      borderRadius: BorderRadius.circular(8),
                      border: Border.all(color: Colors.orange[900]!, width: 2),
                      boxShadow: [
                        BoxShadow(
                          color: Colors.grey.withOpacity(0.5),
                          spreadRadius: 2,
                          blurRadius: 2,
                          offset: const Offset(2, 2),
                        ),
                      ],
                    ),
                    child: Center(
                      child: Text(
                        '$_num1',
                        style: const TextStyle(
                          fontSize: 24,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                  ),
                  const SizedBox(width: 16),
                  Text(
                    _operator,
                    style: const TextStyle(
                        fontSize: 36, fontWeight: FontWeight.bold),
                  ),
                  const SizedBox(width: 16),
                  Container(
                    width: 60,
                    height: 60,
                    decoration: BoxDecoration(
                      color: Colors.yellow[700],
                      borderRadius: BorderRadius.circular(8),
                      border: Border.all(color: Colors.orange[900]!, width: 2),
                      boxShadow: [
                        BoxShadow(
                          color: Colors.grey.withOpacity(0.5),
                          spreadRadius: 2,
                          blurRadius: 2,
                          offset: const Offset(2, 2),
                        ),
                      ],
                    ),
                    child: Center(
                      child: Text(
                        '$_num2',
                        style: const TextStyle(
                          fontSize: 24,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                  ),
                  const SizedBox(width: 16),
                  const Text(
                    '= ',
                    style: TextStyle(fontSize: 36, fontWeight: FontWeight.bold),
                  ),
                ],
              ),
              const SizedBox(height: 32),
              Wrap(
                spacing: 16,
                runSpacing: 16,
                children: _options.map((int option) {
                  final isSelected = _userAnswer == option;
                  print(
                      "选项: $option, isSelected: $isSelected, _userAnswer: $_userAnswer");
                  return ElevatedButton(
                    onPressed: () {
                      print("错误选项被点击: $option");
                      //setState(() {
                      print("setState4");
                      _userAnswer = option;
                      //});
                      _checkAnswer(); // 立即检查答案
                    },
                    style: ElevatedButton.styleFrom(
                      fixedSize: const Size(80, 80),
                      textStyle: const TextStyle(fontSize: 24),
                      backgroundColor:
                          // 仅在回答正确且是正确选项时显示绿色
                          (isSelected && isCorrect)
                              ? Colors.green
                              // 其他情况下保持白色背景
                              : Colors.white,
                      foregroundColor: (isSelected && isCorrect)
                          ? Colors.white
                          : Colors.black,
                    ),
                    child: Text('$option'),
                  );
                }).toList(),
              ),
              const SizedBox(height: 32),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(_feedbackIcon, size: 32, color: _feedbackColor),
                ],
              ),
            ],
            if (!_isLevelCompleted) const SizedBox(height: 32),
            if (!_isLevelCompleted)
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text('得分: $_currentScore',
                      style: const TextStyle(fontSize: 20)),
                ],
              ),
            const SizedBox(height: 16),
            _buildLevelInfoIndicator(),
            const SizedBox(height: 8),
            _TimerDisplay(
              key: _timerKey, // 绑定 GlobalKey
              timeLimit: _currentLevelConfig.timeLimit,
            ),
          ],
        ),
      ),
    );
  }
}
